<script>
import { createNamespacedHelpers } from 'vuex'
import changeIco from '@/assets/icons/change.svg'

const { mapActions } = createNamespacedHelpers('Community')

export default {
  name: 'publish-post',
  data: () => ({
    changeIco,
    imageUrl: '',
    text: ''
  }),
  methods: {
    ...mapActions(['publishPost']),
    handleReplaceImg() {
      wx.chooseImage({
        count: 1,
        success: res => {
          this.imageUrl = res.tempFilePaths[0]
        }
      })
    },

    handleChangeText(e) {
      if (e.mp && e.mp.detail) {
        this.text = e.mp.detail.value
        console.log(this.text)
      }
    },

    handleSubmit() {
      if (this.imageUrl && this.text) {
        wx.showLoading({ title: '发布中...' })
        this.publishPost({ imageUrl: this.imageUrl, text: this.text })
          .then(() => {
            wx.hideLoading()
            wx.navigateBack()
          })
          .catch(() => wx.hideLoading())
      } else {
        wx.showModal({ title: '提示', content: '请选择图片,并填写内容', showCancel: false })
      }
    }
  },

  onLoad(option) {
    console.log('img url', option.img)
    this.imageUrl = option.img
  }
}
</script>

<template>
  <div class="publish-post">
    <div class="img-container">
      <img :src="imageUrl" class="img-preview" mode="aspectFill">
      <div class="img-change" @click="handleReplaceImg">
        <span class="text">换一张</span>
        <img :src="changeIco" class="img-change-icon">
      </div>
    </div>

    <p class="text-title">足迹, 记录好每一步</p>
    <textarea class="text-box" @input="handleChangeText" maxlength="100" />
    <p class="text-tips">字数限制100</p>
    <div class="submit-btn" @click="handleSubmit">发布</div>
  </div>
</template>

<style lang="scss" scoped>
@import './styles.scss';
</style>
